package com.stgy.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stgy.lease.common.exception.StgyException;
import com.stgy.lease.common.result.ResultCodeEnum;
import com.stgy.lease.model.domain.AttrKey;
import com.stgy.lease.model.domain.AttrValue;
import com.stgy.lease.web.admin.service.AttrKeyService;
import com.stgy.lease.web.admin.mapper.AttrKeyMapper;
import com.stgy.lease.web.admin.service.AttrValueService;
import com.stgy.lease.web.admin.vo.AttrKeyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lingx
 * @description 针对表【attr_key(房间基本属性表)】的数据库操作Service实现
 * @createDate 2024-08-28 11:00:28
 */
@Service
public class AttrKeyServiceImpl extends ServiceImpl<AttrKeyMapper, AttrKey>
        implements AttrKeyService {

    @Autowired
    private AttrValueService attrValueService;

    @Override
    public List<AttrKeyVo> listAttrKeyVos() {
        //先查询AttrKey的集合 再遍历查询每个AttrKey的AttrValue子集合
        //自定义sql实现：两表联查(表数据量不大) 量大 创建索引
        return baseMapper.selectAttrKeyVos();
    }

    @Override
    public boolean saveOrUpdateKey(AttrKey attrKey) {
        if (attrKey == null || attrKey.getName() == null) {
            throw new StgyException(ResultCodeEnum.DATA_EXISTS_ERROR);
        }
        LambdaQueryWrapper<AttrKey> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttrKey::getName, attrKey.getName());
        wrapper.last("limit 1");
        AttrKey one = this.getOne(wrapper);
        //唯一校验 type+name 组合唯一
        if (one != null && !one.getId().equals(attrKey.getId())) {
//        if (one != null && one.getId().longValue() != facilityInfo.getId()) {
            throw new StgyException(ResultCodeEnum.DATA_EXISTS_ERROR);
        }

        return this.saveOrUpdate(attrKey);
    }

    @Transactional(rollbackFor = Exception.class) //事务
    @Override
    public boolean deleteByIds(List<Long> ids) {
        if (ids == null) {
            throw new StgyException(ResultCodeEnum.DATA_EXISTS_ERROR);
        }
        this.removeByIds(ids);

        LambdaQueryWrapper<AttrValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AttrValue::getAttrKeyId, ids);
        attrValueService.remove(wrapper);

        return true;
    }
}




